<template>
  <div class="app-container">
    <el-form size="large" :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="78px">
      <el-form-item label="IP地址" prop="requestIp">
        <el-input @blur="handleQuery" v-model="queryParams.requestIp" placeholder="请输入客户端IP地址" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="操作人" prop="operator">
        <el-input @blur="handleQuery" v-model="queryParams.operator" placeholder="请输入操作人" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['project:project:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['project:project:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['project:project:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['project:project:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row> -->

    <el-table border highlight-current-row v-loading="loading" :data="projectList"
      @selection-change="handleSelectionChange">
      <!-- <el-table-column label="请求唯一ID" align="center" prop="requestId" /> -->
      <el-table-column label="模块名称" align="center" prop="moduleName" />
      <!-- <el-table-column label="方法名" align="center" prop="methodName" />
      <el-table-column label="请求URL" align="center" prop="requestUrl" />
      <el-table-column label="GET/POST/PUT/DELETE" align="center" prop="requestMethod" /> -->
      <el-table-column label="IP地址" align="center" prop="requestIp" />
      <!-- <el-table-column label="请求路径，如：/project/goods/page" align="center" prop="uri" /> -->
      <!-- <el-table-column label="查询参数" align="center" prop="requestParams" show-overflow-tooltip /> -->
      <!-- <el-table-column label="查询结果" align="center" prop="responseResult" show-overflow-tooltip /> -->


      <el-table-column label="查询结果" align="center">
        <template #default="scope">
          <el-link type="primary" @click="handleView(scope.row.responseResult)" :underline="false">
            查看结果
          </el-link>
        </template>
      </el-table-column>

      <el-table-column label="操作人" align="center" prop="operator" />
      <el-table-column label="操作时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="view" @click="handleUpdate(scope.row)">详情</el-button>
        </template>
      </el-table-column> -->
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改操作日志记录对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form disabled ref="projectRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="模块名称" prop="moduleName">
          <el-input v-model="form.moduleName" placeholder="请输入模块名称" />
        </el-form-item>
        <el-form-item label="方法名" prop="methodName">
          <el-input v-model="form.methodName" placeholder="请输入方法名" />
        </el-form-item>
        <el-form-item label="请求URL" prop="requestUrl">
          <el-input v-model="form.requestUrl" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="调用方法" prop="requestMethod">
          <el-input v-model="form.requestMethod" />
        </el-form-item>
        <el-form-item label="客户端IP地址" prop="requestIp">
          <el-input v-model="form.requestIp" />
        </el-form-item>
        <el-form-item label="请求路径" prop="uri">
          <el-input v-model="form.uri" />
        </el-form-item>


        <el-form-item label="请求参数" prop="uri">
          <el-input v-model="form.requestParams" />
        </el-form-item>

        <el-form-item label="响应结果" prop="responseResult">
          <el-input v-model="form.responseResult" type="textarea" />
        </el-form-item>
        <el-form-item label="操作人" prop="operator">
          <el-input v-model="form.operator" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button type="primary" @click="submitForm">确 定</el-button> -->
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>

  <el-drawer v-model="openJson" direction="ltr" title="操作记录" :with-header="false" size="50%">
    <el-table border v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
      <el-table-column label="型号" align="center" prop="modal" />
      <el-table-column label="完整名称" align="center" prop="fullName" />
      <el-table-column label="简称" align="center" prop="name" />
      <el-table-column label="历史采购最低价(￥)" align="center" prop="minPrice">
        <template #default="scope">
          <span :style="{ color: '#008c46', fontWeight: '500' }">{{ scope.row.minPrice }}</span>
        </template>
      </el-table-column>
      <el-table-column label="历史采购明细(默认自2019年9月至今)" align="center" prop="historyCostList" min-width="250">
        <template #default="scope">
          <div v-for="(item, index) in scope.row.historyCostList" :key="index" class="record-item">
            <span class="batch">第{{ item.index }}批</span>
            <span class="batch">数量:{{ item.count }}</span>
            <span class="price-label">入库价格:</span>
            <strong class="price-value">{{ item.price }}</strong>
            <span class="date-label">入库日期:</span>
            <strong :style="{ color: '#E6A23C' }">{{ item.date }}</strong>
          </div>
        </template>
      </el-table-column>

      <!-- <el-table-column label="库存余量" align="center" prop="remaining" /> -->

      <el-table-column label="库存余量(全部时间)" align="center">
        <template #default="scope">
          <span :style="{
            color: scope.row.remaining < 0 ? 'red' :
              scope.row.remaining > 0 ? 'green' : '#000',
            fontWeight: 'bold',
            fontSize: '14px'  // 可根据需要调整，比如 16px 加大
          }">
            {{ scope.row.remaining }}
          </span>
        </template>
      </el-table-column>


    </el-table>

  </el-drawer>

</template>

<script setup name="Project">
import { listProject, getProject, delProject, addProject, updateProject } from "@/api/operLog";
import jsonEditor from '../../components/JsonEditor/src/JsonEditor.vue';
import goodsIndex from '../goods/index'

const { proxy } = getCurrentInstance();
const goodsList = ref([]);
const openJson = ref(false)
const curentJson = ref()
function handleView(datas) {
  try {
    // 将 JSON 字符串解析为 JavaScript 对象
    const parsedData = JSON.parse(datas)

    // 现在可以安全访问属性
    curentJson.value = parsedData        // 完整 JSON 显示用
    goodsList.value = parsedData.rows    // 假设后端返回结构中有 .rows 字段

    openJson.value = true                // 打开弹窗
  } catch (error) {
    console.error('JSON 解析失败:', error)
    ElMessage.error('数据格式错误，无法解析 JSON')

    // 可选：显示原始内容或空值
    curentJson.value = { error: 'Invalid JSON', raw: datas }
    goodsList.value = []
    openJson.value = true
  }
}
const projectList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    requestIp: null,
    operator: null,
  },
  rules: {
    requestUrl: [
      { required: true, message: "请求URL不能为空", trigger: "blur" }
    ],
    requestMethod: [
      { required: true, message: "GET/POST/PUT/DELETE不能为空", trigger: "blur" }
    ],
    requestIp: [
      { required: true, message: "客户端IP地址不能为空", trigger: "blur" }
    ],
    uri: [
      { required: true, message: "请求路径，如：/project/goods/page不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询操作日志记录列表 */
function getList() {
  loading.value = true;
  listProject(queryParams.value).then(response => {
    projectList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  // reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    requestId: null,
    moduleName: null,
    methodName: null,
    requestUrl: null,
    requestMethod: null,
    requestIp: null,
    uri: null,
    requestParams: null,
    responseResult: null,
    operator: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    loginIp: null,
    loginDate: null
  };
  // proxy.resetForm("projectRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加操作日志记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  // reset();
  const _id = row.id || ids.value
  getProject(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改操作日志记录";
    console.log("????????", form.value);



  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["projectRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateProject(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addProject(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除操作日志记录编号为"' + _ids + '"的数据项？').then(function () {
    return delProject(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('project/project/export', {
    ...queryParams.value
  }, `project_${new Date().getTime()}.xlsx`)
}

getList();
</script>



<style lang="scss" scoped>
// 自定义当前行的背景颜色
:deep(.el-table .current-row) {
  background-color: #ffebcd !important;
  /* 例如：桃色背景 */
  // 你也可以添加其他样式
  font-weight: bold;
  color: #333;
}

/* 如果你想修改鼠标悬停时的背景色，也可以覆盖 */
:deep(.el-table tbody tr:hover > td) {
  background-color: #ffe4b5 !important;
  /* 悬停颜色 */
}
</style>